
/*******************************************************************************
 * The code below this comment is integral part of the project "Jelliphy".
 * 
 * "Jelliphy" is a project created by: 
 * Dispage - Patrizio Gelosi
 * Via A. De Gasperi 91 
 * P. Potenza Picena (MC) - Italy
 * 
 * (Hereby referred to as "DISPAGE")
 * 
 * Copyright (c) 2011 DISPAGE.
 * 
 * @Released on: 02-06-2011
 * @Version: 1.0.00
 * @Build: 1109
 * @Site: http://www.dispage.com
 * @Contacts: http://www.dispage.com/contacts
 * 
 * The contents of this file are released under the GNU General Public License
 * version 3 as published by the Free Software Foundation that can be found at
 * the address "http://opensource.org/licenses/gpl-3.0.html". If the license
 * cannot be found, write to the Free Software Foundation, Inc., 51 Franklin
 * Street, Fifth Floor, Boston, MA 02110-1301 USA.
 * 
 * You may not use the present file except in compliance with the License.
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License
 * for the specific language governing rights and limitations under the
 * License.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * Dispage" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by Dispage".
 * 
 ******************************************************************************/

var MGGueSel = function () {

	var that = this,
		tgEl = null,
		$tgEl = null,

		wMethCoef = {
			'id'		: 0,
			'name'		: 0.5,
			'class'		: 0.9,
			'idSec'		: 0.95,
			'text'		: 5,
			'tag'		: 10
		},
	
		bestSels = ['id', 'name', 'class'],

		bestSel = [],
			
		
		getElementSelector = function (el, jqsel, label, selType) {

			var numElements = JlQ(jqsel).length,
				weight = (typeof(selType) == 'undefined') ? numElements : numElements * wMethCoef[selType],
				jqselFinal = jqsel,
				labelFinal = label,
				i;

			for (i = 0; i < numElements; i++) {
				if (JlQ(jqsel+':eq('+i+')')[0] == el) {
					if (numElements > 1) {
						jqselFinal += ':eq('+i+')';
						labelFinal += ' ('+(i +1)+' of '+numElements+')';
					}
					if (JlQ.inArray(selType, bestSels) != -1 && (!bestSel.length || weight < bestSel[2])) {
						bestSel = [jqsel, label, weight];
					}
					return [jqselFinal, labelFinal, weight];
				}
			}
			return [];
		},
			
		addElementSelector = function (jqsel, label, selType) {

			var addSel = getElementSelector(tgEl, jqsel, label, selType);

			if (addSel.length) {
				that.selectors.push(addSel);
			}
		},
			
		getInterParentTags = function (toSel) {

			var interParents = $tgEl.parentsUntil(toSel);

			if (interParents.length) {
				return ' > ' + interParents.map(function (i, el) {return el.tagName}).get().reverse(false).join(' > ') + ' > ';
			}
			else {
				return ' > ';
			}
		},

		convertClassName = function (classes) {

			classes = classes.replace(/^ +/, '').replace(/ +$/, '').replace(/ +/g, '.').replace(/(?:^|\.)mg-[^.]+/g, '');
			if (classes) classes = '.' + classes;

			return classes;
		},

		getParentIdSel = function () {

			var curRelated, relFound = $tgEl.parents("[id]:not([id^=mg-]),body"),
				fromSel, parentTag;

			if (!relFound.length) return;
			curRelated = relFound.get(0);
			if (curRelated.tagName == 'BODY') {
				fromSel = 'body';
				parentTag = 'body';
			}
			else {
				fromSel = '#' + curRelated.id;
				parentTag = 'id=' + MGUtils.cutText(curRelated.id, 20);
			}
			addElementSelector(fromSel + getInterParentTags("[id]:not([id^=mg-]),[class]:not([class^=mg-]):not([class^=JLui-]),body") + bestSel[0], parentTag + ' -> ' + bestSel[1], 'idSec');
		},

		getClassSel = function () {

			var curRelated, relFound = $tgEl.parents("[class]:not([class^=mg-]):not([class^=JLui-])"),
				jqRel = [],
				classSel;

			if (!relFound.length) return;
			curRelated = relFound.get(0);
			classSel = convertClassName(curRelated.className);
			jqRel = getElementSelector(curRelated, classSel, 'class='+MGUtils.cutText(classSel, 30));
			if (jqRel.length) {
				addElementSelector(jqRel[0] + getInterParentTags("[id]:not([id^=mg-]),[class]:not([class^=mg-]):not([class^=JLui-])") + bestSel[0], jqRel[1] + ' -> ' + bestSel[1]);
			}
		},

		getSiblingSel = function (which) {

			var relFound = $tgEl.prevAll(which),
				curRelated, classSel;

			if (!relFound.length) return;
			curRelated = relFound.get(0);
			if (which == '[id]:not([id^=mg-])') {
				addElementSelector('#' + curRelated.id + ' ~ ' + bestSel[0], 'id=' + MGUtils.cutText(curRelated.id, 20) + ' ~ ' + bestSel[1]);
			}
			else {
				classSel = convertClassName(curRelated.className);
				if (classSel) {
					addElementSelector(classSel + ' ~ ' + bestSel[0], 'class='+MGUtils.cutText(classSel, 30) + ' ~ ' + bestSel[1]);
				}
			}
		},

		getContentSel = function () {

			var children = $tgEl.children(),
				innerText = $tgEl.text(),
				curId;

			if (children.length) {
				if (JlQ('[id]:not([id^=mg-])', children).length) {
					curId = JlQ('[id]:not([id^=mg-])', children).attr('id');
					addElementSelector(':not([class^=mg-]) > ' + bestSel[0] + ':has(#' + curId + ')', bestSel[1] +  ' -> ' + 'id=' + MGUtils.cutText(curId, 20));
				}
			}
			else if (innerText && innerText.length < 32) {
				addElementSelector(':not([class^=mg-]) > ' + bestSel[0] + ':econtains("' + MGUtils.content2SQString(innerText, {quot : true}) + '"):not([class^=mg-]:not([class=mg-added-absolute-element])):not([class^=JLui-]):not([id^=mg-])', 'text=' + innerText, 'text');
			}
		};



	that.selectors = [];

	that.updateElSelector = function (forceSel) {

		var sels = (typeof(forceSel) == 'undefined') ? that.selectors : forceSel;

		JlQ('#mg-element-selector').html(JlQ.map(sels, function (s) {
			return '<option value="' + MGUtils.text2QCString(s[0]) + '">'+s[1]+'</option>';
		}).join());
	};

	that.populateSelectorList = function ($el, options) {

		var tag, m9t, classSel;

		options = JlQ.extend(options, {});

		that.selectors = [];
		bestSel = [];

		$tgEl = $el;
		tgEl = $el.get(0);

		if (tgEl) {

			if (m9t = $tgEl.attr('m9t')) {
				that.selectors = [['[m9t='+m9t+']', 'm9t='+m9t, -1]];
				return;
			}

			tag = tgEl.tagName;

			if (tag == 'BODY') {
				addElementSelector('body', 'body', 'tag');
			}
			if (tgEl.id && tgEl.id.search(/^mg-/) != -1) {
				addElementSelector('#'+tgEl.id, 'id='+MGUtils.cutText(tgEl.id, 30), 'id');
			}
			classSel = convertClassName(tgEl.className);
			if (classSel)	{
				addElementSelector(classSel, 'class='+MGUtils.cutText(classSel, 30), 'class');
			}
			if (tgEl.name)	{
				addElementSelector(tag+'[name='+tgEl.name+']', 'name='+MGUtils.cutText(tgEl.name, 30), 'name');
			}
			if (!bestSel.length /*|| bestSel[2] > wMethCoef['tag']*/) {
				bestSel = [tag, 'tag=' + tag, wMethCoef['tag']];
			}
			getParentIdSel();
			getClassSel();
			if (!options.exclude || JlQ.inArray('siblings', options.exclude) == -1) {
				getSiblingSel('[id]:not([id^=mg-])');
				getSiblingSel('[class]:not([class^=mg-]):not([class^=JLui-])');
			}
			if ((!options.exclude || JlQ.inArray('content', options.exclude) == -1) && !JlQ.browser.msie) {
				getContentSel();
			}
		}
		if (!that.selectors.length) {
			that.selectors = [['', 'none']];
		}
		else {
			that.selectors = that.selectors.sort(function (a, b) {return a[2] > b[2]});
		}
	};

};